package com.zx.idc.backend.gui.config.aspect;

import com.zx.idc.backend.gui.common.util.NetworkUtil;
import com.zx.idc.backend.gui.shiro.TokenManagerUtil;
import com.zx.idc.common.constants.OperTypeConstants;
import com.zx.idc.common.util.JsonUtil;
import com.zx.idc.common.util.ProcessUtil;
import com.zx.idc.ds.sys.entity.SysUser;
import com.zx.idc.ds.tlog.entity.TLogOperation;
import com.zx.idc.ds.tlog.service.ITLogOperationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;

/**
 * 用户操作日志拦截器
 *
 * @author rxliuli
 */
@Component
public class UserOperatingLogInterceptor implements HandlerInterceptor {
    @Autowired
    private ITLogOperationService tlogOperationService;


    @Autowired
    private TokenManagerUtil tokenManagerUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        final SysUser sysUser = tokenManagerUtil.getCurrentUser();
        if (sysUser != null) {
            final Integer userId = sysUser.getId();
            final String ip = NetworkUtil.getIpAddress(request);
            final String pid = ProcessUtil.getPid();
            final LocalDateTime now = LocalDateTime.now();
            final String uri = request.getRequestURI();
            OperTypeConstants operType = getOperType(request.getMethod(), uri);
            final TLogOperation tlogOperation = new TLogOperation(
                userId,
                JsonUtil.write(request.getParameterMap()),
                operType.getOperType(),
                ip,
                pid,
                uri,
                now,
                ""
            );
            CompletableFuture.runAsync(() -> tlogOperationService.insert(tlogOperation));
        }
        return true;
    }

    /**
     * 获取操作类型 根据url粗略判断
     *
     * @param method
     * @param uri
     * @return
     */
    private OperTypeConstants getOperType(String method, String uri) {
        //get请求
        if (RequestMethod.GET.toString().equals(method)) {
            if (uri.contains("export-data")) {
                //导出
                return OperTypeConstants.EXPORT;
            } else {
                //查询
                return OperTypeConstants.SELECT;
            }
            //post请求
        } else if (RequestMethod.POST.toString().equals(method)) {
            //List.of("insert-report", "update-report").find(uri::contains).isDefined()
            if (uri.contains("report")) {
                //上报
                return OperTypeConstants.UPLOAD;
            } else if (uri.contains("import-data")) {
                //导入
                return OperTypeConstants.IMPORT;
            } else if (uri.contains("add")) {
                //新增
                return OperTypeConstants.CREATE;
            } else if (uri.contains("update")) {
                //更新
                return OperTypeConstants.UPDATE;
            } else if (uri.contains("delete")) {
                //删除
                return OperTypeConstants.DELETE;
            } else if (uri.contains("cancel-handle")) {
                //取消处置
                return OperTypeConstants.CANCEL_HANDEL;
            } else if (uri.contains("handle")) {
                //处置
                return OperTypeConstants.HANDEL;
            } else if (uri.contains("set-trust")) {
                //设置信任
                return OperTypeConstants.SET_TRUST;
            } else if (uri.contains("filing-batch")) {
                //检查
                return OperTypeConstants.CHECK;
            } else if (uri.contains("logout")) {
                //注销
                return OperTypeConstants.LOGOUT;
            }
        }
        return OperTypeConstants.NOT_SET;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}
